$(window).ready(function() {
    var request = GetRequest();

    /*查看分类效果*/
    /*-------*/
    $("#Pagination").pagination("100");
    /*  删除此行 */

    $.ajax({
        url: "/index/getMenu",
        type: 'get',
        async: false,
        success: function (data) {
            var data = data.data;
            if (data != null) {

                var z = 0;//用来转化成数字的中介
                // 导航栏Collections的下拉导航
                var collectionNav_li = "";
                //搜索框左边的分类
                var collectionOpt = "";
                for (var d in data) {
                    collectionNav_li += "<li> <a href=\"collection.html?id=" + data[d].id + "\" class=\"site-nav__link\">" + data[d].name + "</a> </li>";
                    collectionOpt += '<option value="' + data[d].id + '">' + data[d].name + '</option>';
                }
                $("#collectionNav").append(collectionNav_li);
                $("#collection-option").append(collectionOpt);

            }

        }

    });


    var param='';
    $.ajax({
        url: "/product/getAncestorsByCategoryId?categoryId="+request.categoryId,//41
        type: 'get',
        async: false,
        success: function (data) {
            //得到的是list
            param=`<div class="tab-pane fade active in" id=""><div class="detail_informationTop">
								<!-- 类似淘宝的分类 -->`;
            var grade="";
            for(var k in data){
                //从第一级开始,所以得从后面拿
                if(request.categoryId==data[k])
                    grade=`<p><a href="/agriecomIndex/search/paramForward?categoryId=`+data[k]+`">`+ k+` &gt;</a></p>`+grade;   //加在后面
                else {
                        grade = `<p><a href="/collection.html?keyword=&categoryId=` + data[k] + `">` + k + ` &gt;</a></p>` + grade;   //加在后面
                }
            }
            param=param+grade;
        }
    });



//点击三级分类时返回产品参数信息
    $.ajax({
        url: "/product/getParamByCategoryId?categoryId="+request.categoryId,//41
        type: 'get',
        async: false,
        success: function (data) {
            var z=0;
            param+=`<span class="detaInfor_PackUp" style=""><a href="javascript:;">收起分类</a></span></div>
	                <div class="detail_informationContent">
									<div class="detail_informationContentT">
										<ul class="select" style="list-style: none; display: block;">`;
            for (var d in data) {
                z = parseInt(d) + 1;
                param+=`<li class="select-list">
												<dl id="select`+z+`">
												<dt>`+data[d].paramName+`</dt>
												<dd class="select-all selected"><a href="#">全部</a></dd>
												`;
                var paramValues= data[d].produceParamValueList;
                for(var x in paramValues)
                {
                    param+=`<dd><a href="javascript:;">`+paramValues[x].paramValue+`</a></dd>`;
                }
                param+=`</dl></li>`;
            }
                param+=`<li class="select-result">
												<dl id="select0">
													<dt>已选条件：</dt>
													<dd class="select-no">暂时没有选择过滤条件</dd>
												</dl>
											</li>
										</ul>
										<!-- -================正在制作   selected 是背景橙色那个 -->
									</div>
								</div>
							</div>`;


            $("div#myTabContent").append(param);



            let judgeTextFn = (ele) => {
                if ($(ele).children("dl").children("dd").text() === "") {
                    $(ele).children("dl").children("dd").text("暂时没有选择过滤条件");
                }
            };
            let {entries} = Object;
            let newdd1;
            let IdCheck = {};          //*** 里面有动态代码
            z = 0;
            for (let i in data) {
                z = parseInt(i) + 1;
                IdCheck["select" + z] = 'select' +z;
            }
            let removeChildFn = (ele, fDom, clickIndex) => {
                setTimeout(() => {
                    $(ele).eq(0).find(fDom).each((index, ele) => {
                        $(ele).on('click', () => {
                            for (let [key, value] of entries(IdCheck)) {
                                if ($(ele).attr('id') === value) {
                                    $('dl#' + key).find('dd.selected').removeClass('selected').siblings('dd.select-all').addClass('selected');
                                }
                            }
                            $(ele).remove();
                                judgeTextFn(" .select-result");

                            //---------------测试返回原来的位置-------------------
                        });

                    });
                }, 5);


            };      //*** 里面有动态代码
            let ddClickFn = (ele, childDom, selectClass, value, index) => {
                $(ele).children(childDom).click(function () {
                    $(this).addClass("selected").siblings().removeClass("selected");
                    if ($(this).hasClass("selected") === true) {
                        newdd1 = $($(this)).clone();
                        removeChildFn(selectClass, newdd1[0], index);
                        if ($(selectClass).children("dl").children("dd").text() === "暂时没有选择过滤条件") {
                            $(selectClass).children("dl").children("dd").text("").parent().append(newdd1.attr("id", value));
                        }
                        if ($(this).hasClass("select-all") === true) {
                            $(selectClass).children("dl").children("#" + value).remove();
                            if ($(selectClass).children("dl").children("dd").text() === "") {
                                $(selectClass).children("dl").children("dd").text("暂时没有选择过滤条件");
                            }
                        }
                        if ($(this).hasClass("select-all") === false && $(selectClass).children("dl").children("#" + value) != null) {
                            $(selectClass).children("dl").children("#" + value).remove();
                            $(selectClass).children("dl").append(newdd1.attr("id", value));
                        }
                    }
                });

            }
            setTimeout(() => {
                $(".detaInfor_PackUp").click(function () {
                    $(".detaInfor_PackUp").effect('slide', 500);
                    // $(".select").hide(500);
                    if ($(".select").css("display") != "none") {
                        $(".select").hide(500);
                    }
                    else {
                        $(".select").effect("slide", 800);
                    }
                });
                z = 0;
                for (var d in data) {
                    z = parseInt(d) + 1;
                    // ddClickFn("#All #select" + z, "dd", "#All .select-result", IdCheck["select" + z], 0);
                    for (var t in data[d].produceParamValueList) {
                        var x = parseInt(t) + 1;
                        ddClickFn(" #select" + z, "dd", " .select-result", IdCheck["select" + z], d);
                    }

                }
            }, 0);                       //*** 里面有动态代码


            //点击后消失
            var ResultDl = document.getElementById('select0');
            var ddArr = ResultDl.children;

            //---------------------------------
            //收起分类
            $('span.detaInfor_PackUp').each((index, ele) => {
                $(ele).on('click', () => {
                    if ($('div.detail_informationContentT').children('ul').css('display') === 'block') {
                        $(ele).children('a').text('展开分类');
                    } else {
                        $(ele).children('a').text('收起分类');
                    }
                });
            });

        }
    });



    //获取路径中的参数
    function GetRequest() {
        var url = location.search;         //获取url中"?"符后的字串
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            var strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
            }
        }
        return theRequest;
    }


    //点击发送请求
    let AjaxList  = {
        "ArrayList":{},
        "tempData":null,
        "liLength":$('li.select-list').length,
        "dlIdList":{}
    };
    let {entries} = Object;

    for(let i = 0;i<AjaxList["liLength"];i++){
        AjaxList["dlIdList"][i] = $('li.select-list>dl>dt').eq(i).text();
        AjaxList["ArrayList"][$('li.select-list>dl>dt').eq(i).text()] = null;
        //console.log($('li.select-list>dl>dt').eq(i).text()    $('li.select-list>dl').eq(i).attr("id") );
    }
    let page=1;
    let length=8;
    //page对象
    let pageObj=$(".pages").clone(false,true);
    //child对象           防止查找无数据时把元素全部移除导致返回其它查询时无法显示数据
    let childObj=$(".grid-uniform-category>div:first-child").clone(false,true);
    //产品分页函数
    let pageFun=function(jsonStr,categoryId,page,length){
        $(".pages").remove();
        $("#product_wrapper").append(pageObj);
        $(".grid-uniform-category").append(childObj);
        $.ajax({
            url: '/agriecomIndex/search/paramPageSearch?categoryId=' + categoryId+'&page='+ page +'&limit='+length,
            dataType: "json",
            contentType: "application/json",
            type: "POST",
            // data: JSON.stringify(AjaxList["ArrayList"]),
            data:jsonStr,
            success: function (data) {
                console.log(data)
                if(data.count==0){
                    $(".grid-uniform").html("<p style='margin:auto'>暂无数据</p>");
                    $(".pages").remove();
                    return;
                }

                if(data.count<=length){     //不分页
                    $(".pages").remove();
                }else{

                    $("#Pagination").pagination(data.count, {
                        num_edge_entries: 1, //边缘页数
                        num_display_entries: 3, //主体页数
                        callback: pageselectCallback,
                        items_per_page: length, //每页显示1项
                        current_page:page-1,
                        prev_text: "前一页",
                        next_text: "后一页"
                    });
                    /*
                    *       GO页面跳转
                    */
                    $(".searchPage a").bind("click",function(){
                        window.location="/agriecomIndex/search/paramForward?categoryId="+categoryId;
                    });

                    let countPage=data.count%length==0?data.count/length:parseInt(data.count/length)+1;
                    $(".page-sum strong").html(countPage);
                    $(".page-go input").focusout(function(){
                        let desPage=$(".page-go input").val();
                        if (desPage <= countPage &&desPage!=""&&desPage>0) {
                            $(".searchPage a").unbind('click');
                            $(".searchPage a").bind('click',function(){
                                var childDiv=$(".grid-uniform-category>div:first-child").clone(false,true);
                                parentDiv.html("");
                                parentDiv.append(childDiv);
                                pageFun(jsonStr, categoryId, desPage, length);
                            });
                        }
                    })
                    function pageselectCallback(page_index, jq){
                        parentDiv.html("");
                        parentDiv.append(childObj);
                        pageFun(jsonStr, categoryId, page_index+1, length);
                        return false;
                    }



                }
                let parentDiv=$(".grid-uniform-category");
                //点一次就清空

                parentDiv.html("");
                parentDiv.append(childObj);
                $.each(data.data,function(i,ele){
                    //回显

                    var imgDiv=$(".product-image")[i];
                    $(imgDiv.children[0]).attr("href",ele.produceId);
                    $(imgDiv.children[0].children[0]).attr("src",ele.produceImg);
                    var num=i+1;
                    //star
                    $($(".grid-uniform-category>div:nth-child("+num+")>div>div")[1]).remove();
                    $($(".grid-uniform-category>div:nth-child("+num+")>div>div")[0]).after(`<div class="rating-star">
														<span class="spr-badge" id="spr_badge_3008529987" data-rating="0.0">
															<span class="spr-starrating spr-badge-starrating">
																
															</span>
															<span class="spr-badge-caption"> </span>
														</span>
                                    </div>`);
                    //产品名
                    $($(".grid-uniform-category>div:nth-child("+num+")>div>p")[0]).html("");
                    $($(".grid-uniform-category>div:nth-child("+num+")>div>p")[0]).html("<a href='"+ele.produceId+"'>"+ele.produceName+"</a>");
                    //价格
                    var oldPrice=parseFloat(ele.price)+18;
                    $($(".grid-uniform-category>div:nth-child("+num+")>div>p")[1]).html("");
                    $($(".grid-uniform-category>div:nth-child("+num+")>div>p")[1]).html("<strong>On Sale</strong>" +
                        "<span class=\"money\" data-currency-usd=\"$19.99\">"+ele.price+ele.unit+"</span>" +
                        "<span class=\"visually-hidden\">Regular price</span>" +
                        "<s><span class=\"money\" data-currency-usd=\"$24.99\">"+oldPrice+ele.unit+"</span></s>");
                    //排列方式切换（商品简介）
                    $($(".list-mode-description")[i]).html("");
                    $($(".list-mode-description")[i]).html(ele.produceBrief);
                    //联系商家

                    $($(".add-to-cart-form form div")[i]).html("");
                    $($(".add-to-cart-form form div")[i]).html('<a href="/product.html?id='+ele.produceId+'" class="btn btn-1 add-to-cart" title="call now">\n' +
                        '                                                        <i class="fa fa-shopping-cart"></i>联系商家</span>\n' +
                        '                                                    </a>');
                    //拼接
                    var childDiv=$(".grid-uniform-category>div:first-child").clone(false,true);
                    parentDiv.append(childDiv);
                    starChange('span#spr_badge_3008529987',ele.remarks,i);
                })
                $(".grid-uniform-category>div:last-child").empty();
            }

        });

    }
    let categoryIdParam= GetRequest();//json对象
    pageFun('{}', categoryIdParam['categoryId'], page, length);


    $('li.select-list').each((index,ele)=> {
        $(ele).on('click', (e) => {

            //-------------------
            //遍历，如果id相同就覆盖，不同则添加
            for (let [key, values] of entries(AjaxList["dlIdList"])) {
                //console.log($(e.target).parent("dd").parent("dl").children("dt").text());  $(e.target).parent("dd").parent("dl").attr("id")
                if ($(e.target).parent("dd").parent("dl").children("dt").text() === values) {
                    AjaxList["tempData"] = $(e.target).text();
                    AjaxList["ArrayList"][values] = AjaxList["tempData"];
                } else {
                }
            }

            //将AjaxList["ArrayList"]作为$.ajax()参数对象中的data属性值传给后台，下面写请求

            /*//url: '/agriecomIndex/search/paramPageSearch?categoryId=' + param['categoryId'],
            $.ajax({
                url: '/agriecomIndex/search/paramPageSearch?categoryId=' + param['categoryId'],
                dataType: "json",
                contentType: "application/json",
                type: "POST",
                data: JSON.stringify(AjaxList["ArrayList"]),
                success: function (data) {
                }
            });*/
            pageFun(JSON.stringify(AjaxList["ArrayList"]),categoryIdParam['categoryId'],page,length);
            /*   点击参数发送请求   */
            $('li.select-result').on('click', (e) => {
                for (let [key, values] of entries(AjaxList["dlIdList"])) {
                    if ($(e.target).text() === AjaxList["ArrayList"][values]) {
                        AjaxList["ArrayList"][values] = null;
                    }
                }
                pageFun(JSON.stringify(AjaxList["ArrayList"]),categoryIdParam['categoryId'],page,length);
            });

        })
    })
})
let starChange = (str,n=2,index=0)=>{
    let temp = `<i class="spr-icon spr-icon-star" style=""></i>`;
    for(let i=0;i<n;i++){
        $(str).eq(index).find('span.spr-starrating.spr-badge-starrating').append(temp);
    }
}